// pages/food-detail/food-detail.js

const data = require('../../data/index.js')

const globalData = getApp().globalData

Page({

    /**
     * 页面的初始数据
     */
    data: {
        allFoodList: data.foodList,
        food: {}
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        const foods = this.data.allFoodList.find(type => type.type === options.type).foods
        this.setData({ food: Object.assign(foods.find(food => food.value === options.food), { purchaseQuantity: 1 }) })
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    },

    onPurchaseQuantityChange (event) {
        const action = event.currentTarget.dataset.action
        if (action === 'reduce' && this.data.food.purchaseQuantity === 1) {
            return
        }
        action === 'reduce' ? this.data.food.purchaseQuantity-- : this.data.food.purchaseQuantity++
        this.setData({ ['food.purchaseQuantity']: this.data.food.purchaseQuantity })
    },

    onAddShoppingCart () {
        const { unitPrice, purchaseQuantity } = this.data.food
        this.setData({ food: Object.assign(this.data.food, { totalPrice: unitPrice * purchaseQuantity }) })
        globalData.shoppingCartList.push(this.data.food)
        wx.showToast({
            title: '加入成功，正在购物车等亲~~',
            icon: 'none',
            mask: true
        })
    },

    onBuy () {
        const { unitPrice, purchaseQuantity } = this.data.food
        this.setData({ food: Object.assign(this.data.food, { totalPrice: unitPrice * purchaseQuantity }) })
        wx.navigateTo({
            url: '/pages/confirm-order/confirm-order',
            success: res => {
                res.eventChannel.emit(
                    'goConfirmOrder',
                    {
                        selectedFoodList: [this.data.food],
                        orderOrigin: 'foodDetail'
                    }
                )
            }
        })
    }
})